package cn.edu.qlnu.xky.test.common;

import jakarta.servlet.Filter;
import jakarta.servlet.http.HttpFilter;
import jakarta.servlet.http.HttpServletRequest;
import java.io.IOException;
import jakarta.servlet.FilterChain;
import jakarta.servlet.FilterConfig;
import jakarta.servlet.ServletException;
import jakarta.servlet.ServletRequest;
import jakarta.servlet.ServletResponse;

/**
 * Servlet Filter implementation class UserLoginFilter
 */
public class UserLoginFilter extends HttpFilter implements Filter {
       private String[] ignoreUrl ;
       private String[] routeUrl;
    /**
     * @see HttpFilter#HttpFilter()
     */
    public UserLoginFilter() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see Filter#destroy()
	 */
	public void destroy() {
		// TODO Auto-generated method stub
		System.out.println("------过滤器UserLoginFilter销毁了");
	}

	/**
	 * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
	 */
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
		// TODO Auto-generated method stub
		// place your code here
		System.out.println("*****1111 过滤器UserLoginFilter开始验证了");
		HttpServletRequest req = (HttpServletRequest)request;
		String curUri = req.getRequestURI();
		System.out.println("当前的uri="+curUri);
		boolean flag = false;
		for(String route : routeUrl) {
			if(curUri.startsWith(req.getContextPath()+route)) {
				flag=true;
				break;
			}
		}
		if(flag || curUri.equals(req.getContextPath()+"/")) {//flag为true则证明当前资源为静态资源，不需要登录验证
			chain.doFilter(req, response);
			return;
		}
		for(String ignore:ignoreUrl) {
			if(curUri.equals(req.getContextPath()+ignore)) {
				System.out.println("ignoreUrl="+req.getContextPath()+ignore);
				flag = true;
				break;
			}
		}
		if(flag) {
			chain.doFilter(request, response);
		}else {
			//判断是否登录（session中是否有对象curUser),有则通过，没有则跳转到登录页面
			if(req.getSession().getAttribute("curUser") != null) {
				// pass the request along the filter chain
				System.out.println("过滤器中，用户登录验证通过了");
				chain.doFilter(request, response);
			}else {
				request.setAttribute("msg", "非法访问或登录已超时，请登录后访问");
				
				req.getRequestDispatcher("/index.jsp").forward(req, response);
			}
		}		
		System.out.println("*****2222 过滤器UserLoginFilter验证完成了");
	}

	/**
	 * @see Filter#init(FilterConfig)
	 */
	public void init(FilterConfig fConfig) throws ServletException {
		// TODO Auto-generated method stub
		ignoreUrl = fConfig.getInitParameter("ignore").split(";");
		routeUrl = fConfig.getInitParameter("route").split(";");
		System.out.println("++++++++++过滤器UserLoginFilter初始化了");
	}

}
